#import <stdlib.h>
#import "event.h"
#import "eventHandler.h"

///////////////////////////////////////////
//////// EventHandlerConsumer  ///////////
//////////////////////////////////////////

@implementation EventHandlerConsumer

-(id) initWithCommunicator:(id<ICECommunicator>)communicator host:(NSString*)host handler:(EventHandler*)h
{
	[super initWithCommunicator:communicator andHost:host];
	evh = h;
	
	return self;
}

-(void) push:(CollaborationMutableEvent *)evt current:(ICECurrent *)current
{
	Event* ev = [[Event alloc] initWithInternalEvent:evt andCommunicator:[[current adapter] getCommunicator]];
	
	NSUInteger i, size;
	NSMutableArray* v = [[evh objects] retain];
	size = [v count];
	for (i=0; i<size; i++)
	{
		[[v objectAtIndex:i] listen:ev];
	}
	
	[v release];
	[ev release];
}

@end


///////////////////////////////////////////
//////// EventHandlerSupplier   ///////////
//////////////////////////////////////////

@implementation EventHandlerSupplier

-(id) initWithCommunicator:(id<ICECommunicator>)communicator host:(NSString*)host handler:(EventHandler*)h
{
	[super initWithCommunicator:communicator andHost:host];
	evh = h;
	
	return self;
}

@end


///////////////////////////////////////////
////////      EventHandler     ///////////
//////////////////////////////////////////

@implementation EventHandler

-(id) initWithCommunicator:(id<ICECommunicator>)communicator andHost:(NSString*)h
{
	if (![super init])
		return nil;
	
	comm = communicator;
	channel_out = [[EventHandlerSupplier alloc] initWithCommunicator:communicator host:h handler:self];
	channel_input = [[EventHandlerConsumer alloc] initWithCommunicator:communicator host:h handler:self];
	objs = [[NSMutableArray alloc] init];
	
	return self;
}

-(void) dealloc
{
	[channel_out release];
	[channel_input release];
	[objs release];
	
	[super dealloc];
}

-(NSMutableArray*) objects
{
	return objs;
}

-(void) push:(Event*)evt
{
	[channel_out push:[evt internalEvent] current:nil];
}

-(void) registerObject:(ListeningObject*)obj
{
	if ([self objectPosition:obj] == -1)
	{
		[objs addObject:obj];
	}
}

-(void) unregisterObject:(ListeningObject*)obj
{
	int pos = [self objectPosition:obj];
	if (pos != -1)
	{
		[objs removeObjectAtIndex:pos];
	}
}

-(id<ICECommunicator>) communicator
{
	return comm;
}

-(int) objectPosition:(ListeningObject*)obj
{
	int pos = [objs indexOfObject:obj];
	
	if (pos == NSNotFound)
	{
		return -1;
	}
	else return pos;
}

@end
